//! 简化的CREATE TABLE功能测试
//!
//! 测试SQL解析器对CREATE TABLE语句的基本支持

use cdb::{Result, config::DatabaseConfig, sql::QueryEngine, storage::StorageEngine};
use std::sync::Arc;
use parking_lot::RwLock;
use tempfile::TempDir;

#[test]
fn test_create_table_parsing() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 测试基础CREATE TABLE语句解析
    let sql = r#"
        CREATE TABLE users (
            id INTEGER PRIMARY KEY,
            name VARCHAR(100) NOT NULL
        )
    "#;

    // 测试解析是否成功
    let explain_result = query_engine.explain(sql)?;
    
    // 验证解释结果包含CreateTable
    assert!(explain_result.contains("CreateTable"));
    assert!(explain_result.contains("users"));
    
    println!("✅ CREATE TABLE解析测试通过");
    println!("执行计划:\n{}", explain_result);
    Ok(())
}

#[test]
fn test_create_table_execution() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 测试基础CREATE TABLE语句执行
    let sql = r#"
        CREATE TABLE test_table (
            id INTEGER PRIMARY KEY,
            name VARCHAR(50)
        )
    "#;

    let result = query_engine.execute(sql)?;
    
    // 验证结果
    assert_eq!(result.get_affected_rows(), 1);
    assert_eq!(result.rows().len(), 0);
    
    println!("✅ CREATE TABLE执行测试通过");
    Ok(())
}

#[test]
fn test_create_table_with_different_types() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    // 测试不同数据类型的CREATE TABLE语句
    let sql = r#"
        CREATE TABLE type_test (
            id INTEGER,
            name TEXT,
            score REAL,
            is_active BOOLEAN
        )
    "#;

    let result = query_engine.execute(sql)?;
    
    // 验证结果
    assert_eq!(result.get_affected_rows(), 1);
    
    println!("✅ 不同数据类型的CREATE TABLE测试通过");
    Ok(())
}

#[test]
fn test_create_table_performance() -> Result<()> {
    // 创建临时目录
    let temp_dir = TempDir::new().unwrap();
    let data_dir = temp_dir.path().to_path_buf();

    // 创建数据库配置
    let mut config = DatabaseConfig::default();
    config.data_directory = Some(data_dir);

    // 创建存储引擎和查询引擎
    let storage_engine = Arc::new(RwLock::new(StorageEngine::new(&config)?));
    let mut query_engine = QueryEngine::new(storage_engine);

    let start_time = std::time::Instant::now();

    // 创建多个表测试性能
    for i in 0..5 {
        let sql = format!(r#"
            CREATE TABLE perf_test_{} (
                id INTEGER PRIMARY KEY,
                name VARCHAR(100)
            )
        "#, i);

        let result = query_engine.execute(&sql)?;
        assert_eq!(result.get_affected_rows(), 1);
    }

    let elapsed = start_time.elapsed();
    println!("✅ CREATE TABLE性能测试通过");
    println!("创建5个表耗时: {:?}", elapsed);
    println!("平均每个表: {:?}", elapsed / 5);

    // 验证性能要求（每个表创建应该在100ms以内）
    assert!(elapsed.as_millis() < 500, "CREATE TABLE性能不达标");

    Ok(())
}
